package com.imooc.pan.server.common.listener.search;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.imooc.pan.core.utils.IdUtil;
import com.imooc.pan.server.common.event.search.UserSearchEvent;
import com.imooc.pan.server.modules.user.entity.RPanUserSearchHistory;
import com.imooc.pan.server.modules.user.service.RPanUserSearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.lang.management.ClassLoadingMXBean;
import java.util.Date;

/**
 * 用户监听事件监听器
 * @author hhb
 * @data 2024/6/13 23:26
 */
@Component
public class UserSearchEventListener {

    @Autowired
    private RPanUserSearchHistoryService rPanUserSearchHistoryService;

    /**
     * 监听用户搜索事件
     */
    @EventListener(UserSearchEvent.class)
    public void saveSearchHistory(UserSearchEvent event){
        RPanUserSearchHistory rPanUserSearchHistory = new RPanUserSearchHistory();
        rPanUserSearchHistory.setId(IdUtil.get());
        rPanUserSearchHistory.setSearchContent(event.getKeyword());
        rPanUserSearchHistory.setUserId(event.getUserId());
        rPanUserSearchHistory.setCreateTime(new Date());
        rPanUserSearchHistory.setUpdateTime(new Date());
        try{
            rPanUserSearchHistoryService.save(rPanUserSearchHistory);
        }catch (DuplicateKeyException e){
            //更改
            LambdaUpdateWrapper<RPanUserSearchHistory> lqw = new LambdaUpdateWrapper();
            lqw.eq(RPanUserSearchHistory::getUserId,event.getUserId());
            lqw.eq(RPanUserSearchHistory::getSearchContent,event.getKeyword());
            lqw.set(RPanUserSearchHistory::getUpdateTime,new Date());
            rPanUserSearchHistoryService.update(lqw);
        }
    }
}
